package me.pinion.model;


import com.jfinal.plugin.activerecord.Db;
import me.pinion.model.annotation.TableBind;

import java.util.List;

@TableBind(table = "x_favorite")
public class Favorite extends XModel<Favorite> {
    public static Favorite dao = new Favorite();

    public <T extends XModel<T>> List<T> hasFavo(Class<? extends XModel<?>> clazz, User user) {
        ModelType type = ModelType.dao.getByClass(clazz);
        return type.<T>getModelDAO().find("SELECT t.* FROM " + type.getModelTable() + " AS t WHERE t.id in(SELECT f.target_id FROM x_favorite AS f WHERE f.user=? AND f.target_type=?)", user.getId(), type.getId());
    }

    public Favorite hasFavo(XModel<? extends XModel<?>> model, User user) {
        return Favorite.dao.findFirst(
                "SELECT * FROM x_favorite WHERE user=? AND target_id=? AND target_type=?"
                , user.getId()
                , model.getId()
                , model.getModelId());
    }

    public Long count(XModel<? extends XModel<?>> model) {
        return Db.findFirst("SELECT count(f.id) AS favo_count FROM x_favorite as f WHERE f.target_type = ? AND f.target_id = ?", model.getModelId(), model.getId()).getLong("favo_count");
    }
}
